package com.fc.redap.controller;

import com.fc.redap.dtos.ResponseJson;
import com.fc.redap.helper.DateTimeHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.fc.redap.props.UploadFileLocProps;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by E7450 on 2019/1/10.
 */
@RestController
@RequestMapping("/api/file")
@Api(value="文件上传相关的API", tags={"文件上传"})
public class FileController {

    @Value("${upload.file.absolute.path}")
    private String uploadBasePath;

    @Value("${upload.file.static.url.matching}")
    private String uploadStaticMatchingUrl;

     @Autowired
     private UploadFileLocProps ufProps;

    /**
     * 单文件上传
     *
     * @param file
     * @param request
     * @return
     */
    @ApiOperation(value = "POST -- 上传单个文件或图片, 最大100M",
            notes = " REST 方式请求。"+
                    " enctype='multipart/form-data'"+
                    "Request Parameter: <ul>" +
                    "<li><i>必填参数: file: 文件</i></li>" +
                    "</ul>",
            response = ResponseJson.class,
            httpMethod = "POST",
            code = 200
    )
    @PostMapping("/upload")
    @ResponseBody
    public ResponseJson upload(@RequestParam(value="file", required=false) MultipartFile file, HttpServletRequest request)
    {
        String year = DateTimeHelper.getStringFromDate(DateTimeHelper.getCurrentDay(), DateTimeHelper.PAYLOAD_YEAR_ONLY);
        String month = DateTimeHelper.getStringFromDate(DateTimeHelper.getCurrentDay(), DateTimeHelper.PAYLOAD_MONTH_ONLY);
        String yearMonthPath = year + "/" + month + "/";
        String uploadPath = ufProps.getPath() + "/"+ yearMonthPath;
        if (!file.isEmpty())
        {
//            String saveFileName = DateTimeHelper.getCurrentSeconds() + "-" + file.getOriginalFilename();
            String extendName = "";
            if(file.getOriginalFilename() != null)
            {
                int lastIndex = file.getOriginalFilename().lastIndexOf(".");
                if(lastIndex > 0)
                {
                    extendName = file.getOriginalFilename().substring(lastIndex + 1);
                }
            }
            String saveFileName = UUID.randomUUID().toString() + "." + extendName;
            File saveFile = new File(uploadPath + saveFileName);
            if (!saveFile.getParentFile().exists())
            {
                saveFile.getParentFile().mkdirs();
            }
            try
            {
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(saveFile));
                out.write(file.getBytes());
                out.flush();
                out.close();
                return ResponseJson.success(ufProps.getUrl() + yearMonthPath + saveFileName);
            }
            catch (Exception e)
            {
                e.printStackTrace();
                return ResponseJson.error("上传失败," + e.getMessage());
            }
        }
        else
        {
            return ResponseJson.error("上传失败: 上传文件不能为空!");
        }
    }

    /**
     * 多文件上传
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "POST -- 上传多个文件或图片, 最大100M",
            notes = " REST 方式请求。"+
                    " enctype='multipart/form-data'"+
                    "Request Parameter: <ul>" +
                    "<li><i>必填参数: file: 文件</i></li>" +
                    "<li><i>可选参数: file: 文件</i></li>" +
                    "</ul>",
            response = ResponseJson.class,
            httpMethod = "POST",
            code = 200
    )
    @PostMapping("/uploadFiles")
    @ResponseBody
    public ResponseJson uploadFiles(HttpServletRequest request) throws IOException
    {
        String year = DateTimeHelper.getStringFromDate(DateTimeHelper.getCurrentDay(), DateTimeHelper.PAYLOAD_YEAR_ONLY);
        String month = DateTimeHelper.getStringFromDate(DateTimeHelper.getCurrentDay(), DateTimeHelper.PAYLOAD_MONTH_ONLY);
        String yearMonthPath = year + "/" + month + "/";
        String uploadPath = ufProps.getPath() + yearMonthPath;

        File savePath = new File(uploadPath);
        if (!savePath.exists())
        {
            savePath.mkdirs();
        }
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        List<String> updatedFilePathList = new ArrayList<>();
        for (int i = 0; i < files.size(); ++i)
        {
            file = files.get(i);
            if (!file.isEmpty())
            {
                try
                {
                    byte[] bytes = file.getBytes();
                    String saveFileName = DateTimeHelper.getCurrentSeconds() + "-" + file.getOriginalFilename();
                    File saveFile = new File(savePath, saveFileName);
                    stream = new BufferedOutputStream(new FileOutputStream(saveFile));
                    stream.write(bytes);
                    stream.close();
                    updatedFilePathList.add(ufProps.getUrl() + yearMonthPath + saveFileName);
                }
                catch (Exception e)
                {
                    if (stream != null)
                    {
                        stream.close();
                        stream = null;
                    }
                    return ResponseJson.error("第 " + i + " 个文件上传有错误," + e.getMessage());
                }
            }
            else
            {
                return ResponseJson.error("第 " + i + " 个文件为空");
            }
        }
        return ResponseJson.success(updatedFilePathList);
    }
}
